import { useEffect, useState } from 'react';
import { Button, Checkbox, Form, Input, notification, Select } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import styles from './index.module.scss';
import { useDispatch, useSelector } from 'react-redux'
import { setUserInfo } from '@/reducers/main';
import { login } from '@/service'
import { compile, uncompile } from '@/utils'
import { useTranslation } from 'react-i18next';
import Cookies from "js-cookie";
const FormItem = Form.Item;
const Option = Select.Option;

export default props => {
    const [form] = Form.useForm();
    const [notificationApi, contextHolder] = notification.useNotification();
    const [selectedLang, setDefaultlagValue] = useState('en-US');
    const { t, i18n } = useTranslation();
    const initState = () => ({
        loading: false
    }),
        [state, setState] = useState(initState),
        navigate = useNavigate(),
        dispatch = useDispatch();
    // 进入页面判断是否保存了账号密码
    useEffect(() => {
        const userRemberInfo = localStorage.getItem("aws_phase_userRemberInfo");
        // userToken = localStorage.getItem('userToken')
        // // 判断是否登陆 一般使用登录接口返回的Token
        // if (userToken && userinfo) {
        //     navigate('/login');
        // }
        form.setFieldsValue({ 
            userName: '',
            password: '',
            remember: false,
        });
        if (userRemberInfo) {
            const obj = JSON.parse(userRemberInfo);
            form.setFieldsValue({
                userName: obj.userName,
                password: uncompile(obj.password),
                remember: true,
            });
        } else {
            setTimeout(() => {
                document.getElementById("username")?.focus();  // 焦点设置在用户名输入框
            }, 0);
        }
    }, [form, navigate]);
    const onSubmit = async () => {
        try {
            const values = await form.validateFields();
            const { userName, password } = values;
            const params = {
                userName: userName,
                password: password
            };
            setState((prevState) => ({ ...prevState, loading: true }));
            const res = await login(params);
            const { code, message, data } = res || {};
            if (code === 0) {
                const token = data?.token;
                const expire = data?.expire;
                const user = data?.user || {};
                Cookies.set('aws_phase_token', token, { expires: expire });
                dispatch(setUserInfo(user));
                localStorage.setItem("aws_phase_userinfo", compile(JSON.stringify(user)));
                if (form.getFieldValue('remember')) {
                    localStorage.setItem("aws_phase_userRemberInfo", JSON.stringify({ userName, password: compile(password) }));
                } else {
                    localStorage.removeItem("aws_phase_userRemberInfo");
                    form.resetFields();
                }
                navigate(`${BASEDIR}/`);
            } else {
                notificationApi.error({
                    message: 'Login Failed',
                    description: message,
                });
            }
        } catch (error) {
            console.log(error);
            notificationApi.error({
                message: 'Login Failed',
                description: error.message,
            });
        } finally {
            setState((prevState) => ({ ...prevState, loading: false }));
        }
    };
    const handleLanguageChange = (value) => {
        i18n.changeLanguage(value);
        localStorage.setItem('aws_phase_language', value);  // 持久化语言选择
        setDefaultlagValue(value);
    };
    useEffect(() => {
        const savedLanguage = localStorage.getItem('aws_phase_language') || 'en-US';
        setDefaultlagValue(savedLanguage);
        i18n.changeLanguage(savedLanguage);
    }, [i18n]);
    return (
        <div className={styles['container']}>
            <div className={styles.logo}>
                {/* {t('login.management')} */}
                {/* <img src="/public/images/logo.svg" alt="" /> */}
                {/* <div className={styles.logoText}></div> */}
                <div>
                    <Select value={selectedLang}
                        style={{ width: '100px' }} onChange={handleLanguageChange}>
                        <Option value="en-US">English</Option>
                        <Option value="zh_CN">中文</Option>
                        <Option value="ja_JP">日語</Option>
                    </Select>
                </div>
            </div>
            <div className={styles.item}>
                {/* <div className={styles.left}>
                    <div>Welcome</div>
                    <div>每一次等待，都是离知识更近一步的证明。</div>
                    <img src="/public/images/loginBg.svg" alt="" />
                </div> */}
                <div className={styles.right}>
                    <div className={styles.title}>{t('login.welcome')}</div>
                    <Form
                        form={form}
                        style={{ width: 340, margin: '0 auto' }}
                        wrapperCol={{
                            span: 24,
                        }}
                        autoComplete="new-password"
                        className={styles.loginForm}
                    >
                        <FormItem
                            name="userName"
                            rules={[{ required: true, message: t('login.usernameRules') }]}
                        >
                            <Input id='username' prefix={
                                <UserOutlined style={{ color: '#4e5969' }} />} type="text" autoComplete="off" placeholder={t('login.userNamePlaceholder')} />
                        </FormItem>
                        <FormItem
                            name="password"
                            rules={[{ required: true, message: t('login.passwordRules') }]}
                        >
                            <Input.Password
                                prefix={
                                    <LockOutlined style={{ color: '#4e5969' }} />
                                }
                                placeholder={t('login.passwordPlaceholder')} autoComplete="new-password" />
                        </FormItem>
                        <FormItem name="remember" valuePropName="checked">
                            <Checkbox className='custom-checkbox'>{t('login.remember')}</Checkbox>
                        </FormItem>
                        <FormItem>
                            <Button loading={state?.loading} onClick={onSubmit} type="primary" htmlType="submit" className='custom-btn-primary' style={{ width: '144px', display: 'block', margin: '0 auto', height: '48px', lineHeight: '14px' }}>
                                {t('login.loginBtn')}
                            </Button>
                        </FormItem>
                    </Form>
                </div>
            </div>
            {contextHolder}
        </div>
    )
}
